<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\model\Base;
use think\App;
use think\exception\ValidateException;
use think\exception\HttpResponseException;
use think\Validate;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db;
/**
 * 控制器基础类
 */
abstract class BaseController
{
	protected $system;
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = ['lizhili_index_init'];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
        $base= new Base();
        //系统配置
        if(env('app_debug',false)){
            $system=$base->getsystem();
        }else{
            if(!$system=Cache::get('system')){
                $system=$base->getsystem();
                Cache::set('system',$system,3600);
            }
        }
		$this->system=$system;
        View::assign('system', $system);
        //分配广告
        if(env('app_debug',false)){
            $ad=$base->ad();
        }else{
            if(!$ad=Cache::get('ad')){
                $ad=$base->ad();
                Cache::set('ad',$ad,3600);
            }
        }
        View::assign('ad', $ad);

        //使用缓存
        $action=request()->action();
        $id=input('id');
        if($action=='index'){
            if(env('app_debug')){
                $dataindex=[
                    'catename'=>'首页',
                    'en_name'=>'index',
                    'fid'=>0,
                    'cateid'=>0
                ];
            }else{
                if(!$dataindex=Cache::get('dataindex'.$id)){
                    $dataindex=[
                        'catename'=>'首页',
                        'en_name'=>'index',
                        'fid'=>0,
                        'cateid'=>0
                    ];
                    Cache::set('dataindex',$dataindex,3600);
                }
            }
            View::assign('data', $dataindex);
        }

        if($action=='cate'){
            if(env('app_debug')){
                $datacate=(new \app\index\model\Cate())->find($id);
            }else{
                if(!$datacate=Cache::get('datacate'.$id)){
                    $datacate=(new \app\index\model\Cate())->find($id);
                    Cache::set('datacate'.$id,$datacate,3600);
                }
            }
            if(!$datacate){
                header("Location:/404.html");
                die;
            }
            $datacate['cateid']=$id;
            View::assign('data', $datacate);
            //这里做跳转判断
            if($datacate['tiao_type']==1){
				redirect((string)url('index/cate', ['id' => $datacate['tiao_id']]));
			}
			if($datacate['tiao_type']==2){
				redirect((string)url('index/show', ['id' => $datacate['tiao_id']]));
			}
        }

        if($action=='show'){
            if(env('app_debug')){
                $dataarticle=(new \app\index\model\Article())->find($id);
                if(!$dataarticle){
                    header("Location:/404.html");
                    die;
                }
                $datacate=(new \app\index\model\Cate())->find($dataarticle['cateid']);
                $dataarticle['catename']=$datacate['catename'];
                $dataarticle['en_name']=$datacate['en_name'];
                $dataarticle['fid']=$datacate['fid'];
                $dataarticle['cateid']=$datacate['id'];
            }else{
                if(!$dataarticle=Cache::get('dataarticle'.$id)){
                    $dataarticle=(new \app\index\model\Article())->find($id);
                    if(!$dataarticle){
                        header("Location:/404.html");
                        die;
                    }
                    $datacate=(new \app\index\model\Cate())->find($dataarticle['cateid']);
                    $dataarticle['catename']=$datacate['catename'];
                    $dataarticle['en_name']=$datacate['en_name'];
                    $dataarticle['fid']=$datacate['fid'];
                    $dataarticle['cateid']=$datacate['id'];
                    Cache::set('dataarticle'.$id,$dataarticle,3600);
                }
            }
            View::assign('data', $dataarticle);
        }

        $cateid=0;
        if($action=='show'){
            $cateid	=(new \app\index\model\Article())->where('id',$id)->value('cateid');
        }
        if($action=='cate'){
            $cateid = $id;
        }
        View::assign('cateid', $cateid);
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }
    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
        }

        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];
        $type = $this->getResponseType();
        if ($type == 'html'){
            $response = view($this->app->config->get('app.dispatch_success_tmpl'), $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
        }

        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        if ($type == 'html'){
            $response = view($this->app->config->get('app.dispatch_error_tmpl'), $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        throw new HttpResponseException($response);
    }
    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
    }

    /**
     * @param $data
     * @param $time
     * @param false $lei
     * @return array
     */
    protected function jisuan($data, $time=0, $lei=false)
    {
        if(time()-$time/1000 > 6000){
            return ['code'=>0,'msg'=>'时间超时'];
        }
        if (!isset($data['type'])) {
            return ['code'=>0,'msg'=>'非法调用'];
        }
        if(!$lei){
            if (request()->header()["token"]!='461f6924bed805723485e08b985049ebbb3a9774') {
                return ['code'=>0,'msg'=>''];
            }
        }
        $app_key=$data['app_key'];
        unset($data['app_key']);
        ksort($data);
        $str =http_build_query($data, '', '&', PHP_QUERY_RFC3986);
        if (md5($str.'197686741c09329446b110070f88f54d')!=$app_key) {
            return ['code'=>0,'msg'=>'算法不对'];
        }
        return ['code'=>10000,'msg'=>''];
    }

    /**
     * @param $method
     * @param $args
     */
    public function __call($method, $args)
    {
        //重定向浏览器
        header("Location:/404.html");
        //确保重定向后，后续代码不会被执行
        exit;
    }

}
